package com.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import com.bean.BaseBean;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.xike.util.MLog;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class HttpClient extends AsyncHttpClient {

	@Override
	public RequestHandle get(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) {
		return super.get(context, url, params, responseHandler);
	}

	@Override
	public RequestHandle post(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) {
		MLog.e("HttpClient", "url:" + url);
		return super.post(context, url, params, responseHandler);
	}

	@Override
	public RequestHandle get(Context context, String url, ResponseHandlerInterface responseHandler) {
		MLog.e("HttpClient", "url:" + url);
		return super.get(context, url, responseHandler);
	}

	@Override
	public RequestHandle put(String url, ResponseHandlerInterface responseHandler) {
		MLog.e("HttpClient", "url:" + url);
		return super.put(url, responseHandler);
	}

	public BaseBean postFilesContent(String mainUrl, List<String> fileNameList, ArrayList<BasicNameValuePair> params) {
		int TIME_OUT = 120 * 1000;
		String CHARSET = "utf-8";
		String CONTENT_TYPE = "multipart/form-data";
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString();
		String PREFIX = "--", LINE_END = "\r\n";

		try {
			URL url = new URL(mainUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			// conn.setRequestProperty("Charset", CHARSET);
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			StringBuffer sb = new StringBuffer();

			for (BasicNameValuePair param : params) {

				if (StringUtil.isNotNull(param.getValue())) {
					// content 参数
					sb.append(PREFIX);
					sb.append(BOUNDARY);
					sb.append(LINE_END);
					// sb.append("Content-Disposition: form-data;name=\"content\"" + LINE_END);
					sb.append("Content-Disposition: form-data;name=\"" + param.getName() + "\"" + LINE_END);
					sb.append(LINE_END);
					sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));
					sb.append(LINE_END);
				}

			}
			 MLog.e("sb", "" + sb.toString());

			dos.write(sb.toString().getBytes());
			// 图片
			if (fileNameList != null && fileNameList.size() > 0) {
				for (String strFileName : fileNameList) {
					File file = new File(strFileName);
					StringBuffer sbPic = new StringBuffer();
					sbPic.append(PREFIX);
					sbPic.append(BOUNDARY);
					sbPic.append(LINE_END);
					sbPic.append("Content-Disposition: form-data;name=\"pictures\";filename=\"" + strFileName + "\"" + LINE_END);
					sbPic.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
					sbPic.append(LINE_END);

					dos.write(sbPic.toString().getBytes());
					DataInputStream is = new DataInputStream(new FileInputStream(file));

					byte[] bytes = new byte[1024];
					int len = 0;
					while ((len = is.read(bytes)) != -1) {
						dos.write(bytes, 0, len);
					}
					is.close();
					dos.write(LINE_END.getBytes());
				}
			}

			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
			dos.write(end_data);
			dos.flush();
			// int cc = conn.getResponseCode();
			{
				InputStreamReader input = new InputStreamReader(conn.getInputStream());
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				result = sb1.toString();
			}
			BaseBean base_result;
			Gson gson = new Gson();
			base_result = gson.fromJson(result, BaseBean.class);
			return base_result;

		} catch (MalformedURLException e) {
			e.printStackTrace();
			result = "error:net wrong";
		} catch (IOException e) {
			e.printStackTrace();
			result = "error:io wrong";
		}
		return null;
	}

	public String postFileContent(String mainUrl, String fileName, ArrayList<BasicNameValuePair> params) {
		int TIME_OUT = 120 * 1000;
		String CHARSET = "utf-8";
		String CONTENT_TYPE = "multipart/form-data";
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString();
		String PREFIX = "--", LINE_END = "\r\n";

		try {
			URL url = new URL(mainUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			// conn.setRequestProperty("Charset", CHARSET);
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			StringBuffer sb = new StringBuffer();

			for (BasicNameValuePair param : params) {

				if (StringUtil.isNotNull(param.getValue())) {
					// content 参数
					sb.append(PREFIX);
					sb.append(BOUNDARY);
					sb.append(LINE_END);
					// sb.append("Content-Disposition: form-data;name=\"content\"" + LINE_END);
					sb.append("Content-Disposition: form-data;name=\"" + param.getName() + "\"" + LINE_END);
					sb.append(LINE_END);
					sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));
					sb.append(LINE_END);
				}

			}
			MLog.e("sb", "" + sb.toString());

			dos.write(sb.toString().getBytes());
			// 图片
			if (StringUtil.isNotNull(fileName)) {
				File file = new File(fileName);
				StringBuffer sbPic = new StringBuffer();
				sbPic.append(PREFIX);
				sbPic.append(BOUNDARY);
				sbPic.append(LINE_END);
				sbPic.append("Content-Disposition: form-data;name=\"picture\";filename=\"" + fileName + "\"" + LINE_END);
				sbPic.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
				sbPic.append(LINE_END);

				dos.write(sbPic.toString().getBytes());
				Log.e("sbPic", ""+sbPic.toString());
				DataInputStream is = new DataInputStream(new FileInputStream(file));

				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
			}

			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
			dos.write(end_data);
			dos.flush();
			// int cc = conn.getResponseCode();
			{
				InputStreamReader input = new InputStreamReader(conn.getInputStream());
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				result = sb1.toString();
			}
			Log.e("postFileContent", "result:" + result);
			return result;

		} catch (MalformedURLException e) {
			e.printStackTrace();
			result = "error:net wrong";
		} catch (IOException e) {
			e.printStackTrace();
			result = "error:io wrong";
		}
		return null;
	}

	public String postBitmapContent(String mainUrl, Bitmap bitmap, String paramName, ArrayList<BasicNameValuePair> params) {
		int TIME_OUT = 120 * 1000;
		String CHARSET = "utf-8";
		String CONTENT_TYPE = "multipart/form-data";
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString();
		String PREFIX = "--", LINE_END = "\r\n";

		try {
			URL url = new URL(mainUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			// conn.setRequestProperty("Charset", CHARSET);
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			StringBuffer sb = new StringBuffer();

			for (BasicNameValuePair param : params) {
				// content 参数
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				// sb.append("Content-Disposition: form-data;name=\"content\"" + LINE_END);
				sb.append("Content-Disposition: form-data;name=\"" + param.getName() + "\"" + LINE_END);
				sb.append(LINE_END);
				sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));
				sb.append(LINE_END);
			}
			// MLog.e("sb", "" + sb.toString());
			dos.write(sb.toString().getBytes());
			// 图片
			StringBuffer sbPic = new StringBuffer();
			sbPic.append(PREFIX);
			sbPic.append(BOUNDARY);
			sbPic.append(LINE_END);
			sbPic.append("Content-Disposition: form-data;name=\"" + paramName + "\";filename=\"" + "temp.jpg" + "\"" + LINE_END);
			sbPic.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
			sbPic.append(LINE_END);
			dos.write(sbPic.toString().getBytes());

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
			InputStream is = new ByteArrayInputStream(baos.toByteArray());

			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = is.read(bytes)) != -1) {
				dos.write(bytes, 0, len);
			}
			is.close();
			dos.write(LINE_END.getBytes());

			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
			dos.write(end_data);
			dos.flush();
			// int cc = conn.getResponseCode();
			{
				InputStreamReader input = new InputStreamReader(conn.getInputStream());
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				result = sb1.toString();
			}
			MLog.e("postFileContent", "result:" + result);
			return result;

		} catch (MalformedURLException e) {
			e.printStackTrace();
			result = "error:net wrong";
		} catch (IOException e) {
			e.printStackTrace();
			result = "error:io wrong";
		}
		return null;
	}

}
